"use strict";

define('ShopAroundView', [
  'jquery', 'underscore', 'backbone', 'api',
  'LocationCollection', 'CategoryCollection',
  'WareListView',
  'text!templates/shopAround/index.html'
], function ($, _, Backbone, api,
             LocationCollection, CategoryCollection,
             WareListView,
             tpl) {
  return Backbone.View.extend({

    initialize: function () {
      this.template = _.template(tpl);
    },

    events: {
      "click input[id=customerQuery]": "customerQuery"
    },

    customerQuery: function () {
      let self = this;
      var locationId = $('#selector_loc option:selected').attr('id');
      var categoryId = $('#selector_cate option:selected').attr('id');
      if (!this.wareListView) this.wareListView = new WareListView();
      this.wareListView.locationId = locationId;
      this.wareListView.categoryId = categoryId;
      this.wareListView.render(function () {
        //console.log('wareListView render cb');
        $('#customer_query_result').html(self.wareListView.el);
      });
    },

    getData_locations: function (cb) {
      var locations = new LocationCollection();
      locations.fetch({
        success: function (collection) {
          cb && cb(null, collection);
        },
        error: function (coll, res) {
          cb && cb(coll, null);
        }
      });
    },

    getData_categories: function (cb) {
      var categories = new CategoryCollection();
      categories.fetch({
        success: function (collection) {
          cb && cb(null, collection);
        },
        error: function (coll, res) {
          cb && cb(coll, null);
        }
      });
    },

    render: function (cb) {
      var self = this;
      let data = {locations: [], categories: []};

      self.getData_locations(function (err, collection) {
        if (collection) data.locations = collection.toJSON();
        self.getData_categories(function (err, collection) {
          if (collection) data.categories = collection.toJSON();
          let tmpl = self.template(data);
          $(self.el).html(tmpl);
          cb && cb();
        });
      });
    }

  });
});
